package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AddressManagementMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = AddressManagementService.class)
@Transactional
public class AddressManagementServiceImpl implements AddressManagementService {
    @Autowired
    private AddressManagementMapper addressManagementMapper;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
       Page<Address> all= addressManagementMapper.findPage(queryPageBean.getQueryString());
        for (Address address : all) {
            address.setImg("http://q7mxlxf7o.bkt.clouddn.com/"+address.getImg());
        }
        return new PageResult(all.getTotal(),all.getResult());
    }

    @Override
    public Address findById(Integer id) {
      return  addressManagementMapper.findById(id);
    }

    @Override
    public void delById(Integer id) {
        addressManagementMapper.delById(id);
    }

    @Override
    public void add(Address address) {
        addressManagementMapper.add(address);
    }

    @Override
    public void update(Address address) {
        addressManagementMapper.update(address);
    }

    /**
     * 移动端使用的方法
     */
    @Override
    public List<Address> findAll() {
       List<Address> addressList= addressManagementMapper.findAll();
       return addressList;
    }

    @Override
    public List<Address> findHotAddress() {
       List<HashMap<String,Integer>> maps= addressManagementMapper.findHotAddressId();
       List<Integer> ids=new ArrayList<>();
       if(maps.size()<3){
           //获取所有的热门城市
           for (HashMap<String, Integer> map : maps) {
               Integer addressId =map.get("addresssId");
               ids.add(addressId);
           }
       }else {
           //获取前三个热门城市
           for (int i = 0; i < 3; i++) {
               HashMap<String, Integer> map = maps.get(i);
               Integer addressId =map.get("addresssId");
               ids.add(addressId);
           }
       }
        List<Address> addressList=new ArrayList<>();
        for (Integer id : ids) {
            Address address = addressManagementMapper.findById(id);
            addressList.add(address);
        }
        return addressList;
    }
}
